package com.uzai.console.service.turnlink.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.uzai.common.dto.goods.TextConvertGoodsDto;
import com.uzai.common.enums.PlatformTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.console.common.SelectVo;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.turnlink.GenerateShortUrlDto;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.feign.turnlink.TbPwdAnalysisDto;
import com.uzai.console.dto.turnlink.TurnLinkGenerateDto;
import com.uzai.console.dto.turnlink.TurnLinkGoodsAnalyzeDto;
import com.uzai.console.dto.turnlink.TurnLinkLeagueSettingDto;
import com.uzai.console.dto.turnlink.TurnShortLinkDto;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.MarketingActivityMapper;
import com.uzai.console.mapper.TlLeagueSettingMapper;
import com.uzai.console.service.dy.DyTokenService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.feign.dto.ConvertGoodsDto;
import com.uzai.console.service.jd.JdTokenService;
import com.uzai.console.service.locallive.TlbTokenService;
import com.uzai.console.service.pdd.PddTokenService;
import com.uzai.console.service.sysdomain.SysDomainService;
import com.uzai.console.service.tb.tbtoken.TbTokenService;
import com.uzai.console.service.turnlink.TurnLinkService;
import com.uzai.console.service.vph.VphTokenService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.feign.turnlink.TbPwdAnalysisVo;
import com.uzai.console.vo.turnlink.TurnLinkGenerateVo;
import com.uzai.console.vo.turnlink.TurnLinkGoodsAnalyzeVo;
import com.uzai.console.vo.turnlink.TurnLinkLeagueSettingVo;
import com.uzai.console.vo.turnlink.TurnLinkLeagueSettingVo.TurnLinkLeagueSettingAccount;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2022/11/3 15:46
 */
@Service
@Slf4j
public class TurnLinkServiceImpl extends ServiceImpl<TlLeagueSettingMapper, TlLeagueSettingDo> implements TurnLinkService {


    @Autowired
    private TlLeagueSettingRelService tlLeagueSettingRelService;

    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;

    @Autowired
    private ClientApiService clientApiService;

    @Autowired
    private SysDomainService sysDomainService;

    @Autowired
    private TbTokenService tbTokenService;
    @Autowired
    private JdTokenService jdTokenService;
    @Autowired
    private PddTokenService pddTokenService;
    @Autowired
    private VphTokenService vphTokenService;
    @Autowired
    private DyTokenService dyTokenService;
    @Autowired
    private TlbTokenService tlbTokenService;
    @Autowired
    private MarketingActivityMapper marketingActivityMapper;

    @Override
    public List<Long> saveTurnLinkLeagueSetting(Long merId, List<TurnLinkLeagueSettingDto> turnLinkSettings) {

        List<Long> result = new ArrayList<>(turnLinkSettings.size());
        // 遍历
        for (TurnLinkLeagueSettingDto turnLinkSetting : turnLinkSettings) {
            boolean save = Objects.isNull(turnLinkSetting.getId());

            TlLeagueSettingDo record = new TlLeagueSettingDo();
            record.setExt(Objects.isNull(turnLinkSetting.getExt()) ? "" : turnLinkSetting.getExt().toJSONString());
            if (save) {
                if (existsPlatform(merId, turnLinkSetting.getPlatform())) {
                    throw new BusinessException("转链联盟平台配置重复");
                }
                record.setMerId(merId);
                record.setPlatform(turnLinkSetting.getPlatform());
                record.setCreateTime((int) (DateUtil.date().getTime() / 1000L));
            }
            record.setUpdateTime((int) (DateUtil.date().getTime() / 1000L));
            record.setId(save ? IdWorker.getId() : turnLinkSetting.getId());

            this.saveOrUpdate(record);

            result.add(record.getId());

            // 处理关联的账号
            List<TurnLinkLeagueSettingDto.TurnLinkLeagueSettingAccount> relAccounts = turnLinkSetting.getRelAccounts();
            // 删除老的记录
            tlLeagueSettingRelService.deleteBySettingId(merId, record.getId());

            if (CollectionUtil.isEmpty(relAccounts)) {
                continue;
            }

            // 生成新的记录
            List<TlLeagueSettingRelDo> saveAccountRecords = new ArrayList<>(relAccounts.size());
            for (TurnLinkLeagueSettingDto.TurnLinkLeagueSettingAccount relAccount : relAccounts) {

                TlLeagueSettingRelDo tlLeagueSettingRelDo = new TlLeagueSettingRelDo();

                tlLeagueSettingRelDo.setTlLeagueSettingId(record.getId());
                tlLeagueSettingRelDo.setLeagueAccountId(relAccount.getAccountId());
                tlLeagueSettingRelDo.setAccountType(relAccount.getAccountType());
                tlLeagueSettingRelDo.setExt(CollectionUtil.isEmpty(relAccount.getPromotion()) ? "" : JSON.toJSONString(relAccount.getPromotion()));
                tlLeagueSettingRelDo.setMerId(merId);
                tlLeagueSettingRelDo.setPlatform(turnLinkSetting.getPlatform());
                tlLeagueSettingRelDo.setCreateTime((int) (DateUtil.date().getTime() / 1000L));
                tlLeagueSettingRelDo.setUpdateTime((int) (DateUtil.date().getTime() / 1000L));
                tlLeagueSettingRelDo.setId(IdWorker.getId());
                saveAccountRecords.add(tlLeagueSettingRelDo);
            }
            tlLeagueSettingRelService.saveOrUpdateBatch(saveAccountRecords);
        }
        return result;
    }

    private boolean existsPlatform(Long merId, Integer platform) {
        LambdaQueryWrapper<TlLeagueSettingDo> condition = Wrappers.lambdaQuery(TlLeagueSettingDo.class);
        condition.eq(TlLeagueSettingDo::getMerId, merId).eq(TlLeagueSettingDo::getPlatform, platform);

        int count = this.count(condition);
        return count > 0;
    }

    @Override
    public List<TurnLinkLeagueSettingVo> getTurnLinkLeagueSetting(Long merId) {

        List<TurnLinkLeagueSettingVo> result = new ArrayList<>();

        LambdaQueryWrapper<TlLeagueSettingDo> condition = Wrappers.lambdaQuery(TlLeagueSettingDo.class);
        condition.eq(TlLeagueSettingDo::getMerId, merId);
        List<TlLeagueSettingDo> settingList = this.list(condition);

        if (CollectionUtil.isEmpty(settingList)) {
            fillDefaultSetting(result);
            return result;
        }

        List<Long> settingIds = settingList.stream().map(TlLeagueSettingDo::getId).collect(Collectors.toList());
        // 查询关联的账号
        List<TlLeagueSettingRelDo> relList = tlLeagueSettingRelService.listBySettingIds(merId, settingIds);

        // 遍历
        for (TlLeagueSettingDo tlLeagueSettingDo : settingList) {
            TurnLinkLeagueSettingVo item = convertFromDo(tlLeagueSettingDo);
            // 关联的账号信息
            List<TurnLinkLeagueSettingAccount> relAccounts = convertFromDo(relList.stream().filter(record -> item.getId().equals(record.getTlLeagueSettingId())).collect(Collectors.toList()));
            // 填充账号信息
            fillLeagueAccountInfo(merId, tlLeagueSettingDo, relAccounts);
            // 如果平台是淘宝解析域名配置
            fillDomainInfoWithTb(merId, item);

            item.setRelAccounts(relAccounts);
            result.add(item);
        }

        return result;
    }

    private void fillDefaultSetting(List<TurnLinkLeagueSettingVo> result) {
        TurnLinkLeagueSettingVo tbLeagueSettingVo = new TurnLinkLeagueSettingVo();
        tbLeagueSettingVo.setPlatform(PlatformTypeEnum.PT_TAOBAO_VALUE);
        JSONObject ext = new JSONObject();
        ext.put("middle_page_domain", 0);
        tbLeagueSettingVo.setExt(ext);

        result.add(tbLeagueSettingVo);
        result.add(new TurnLinkLeagueSettingVo().setPlatform(PlatformTypeEnum.PT_JD_VALUE));
        result.add(new TurnLinkLeagueSettingVo().setPlatform(PlatformTypeEnum.PT_PDD_VALUE));
        result.add(new TurnLinkLeagueSettingVo().setPlatform(PlatformTypeEnum.PT_VPH_VALUE));
        result.add(new TurnLinkLeagueSettingVo().setPlatform(PlatformTypeEnum.PT_DY_VALUE));
        result.add(new TurnLinkLeagueSettingVo().setPlatform(PlatformTypeEnum.PT_KS_VALUE));
    }

    private void fillDomainInfoWithTb(Long merId, TurnLinkLeagueSettingVo tlLeagueSettingDo) {

        Integer platform = tlLeagueSettingDo.getPlatform();

        if (PlatformTypeEnum.PT_TAOBAO.getId().equals(platform)) {
            JSONObject ext = tlLeagueSettingDo.getExt();
            if (Objects.isNull(ext)) {
                log.warn("turn link tb settings parse is null");
                return;
            }
            Long middle_page_domain = ext.getLong("middle_page_domain");
            if (Objects.equals(middle_page_domain, -1L)) {
                tlLeagueSettingDo.setLinkUrl(StringUtils.defaultString(ext.getString("middle_page_link"), ""));
            }
            // 非页面参数
            else {
                SysDomain byId = sysDomainService.getById(merId, middle_page_domain);
                if (Objects.nonNull(byId)) {
                    tlLeagueSettingDo.setLinkUrl(byId.getSiteDomain());
                }
            }
        }
    }

    private static void filterTokenAccountId(List<TurnLinkLeagueSettingAccount> relAccounts, List<Long> vphAccountIds, List<Long> vphTlbAccountIds) {
        for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
            if (Objects.isNull(relAccount.getAccountType())) {
                vphAccountIds.add(relAccount.getAccountId());
                continue;
            }
            if (Objects.equals(relAccount.getAccountType(), ACCOUNT_TYPE_0)) {
                vphAccountIds.add(relAccount.getAccountId());
            } else if (Objects.equals(relAccount.getAccountType(), ACCOUNT_TYPE_1)) {
                vphTlbAccountIds.add(relAccount.getAccountId());
            }
        }
    }

    private void fillLeagueAccountInfo(Long merId, TlLeagueSettingDo tlLeagueSettingDo, List<TurnLinkLeagueSettingAccount> relAccounts) {

        Integer platform = tlLeagueSettingDo.getPlatform();

        // 获取到所有的联盟账号ID
        List<Long> leagueAccountIds = relAccounts.stream().map(TurnLinkLeagueSettingAccount::getAccountId).distinct().collect(Collectors.toList());
        if (ObjectUtils.isEmpty(leagueAccountIds)) {
            return;
        }
        switch (platform) {
            // 淘宝
            case 0:
                List<TbToken> tbTokens = tbTokenService.listTbToken(merId, leagueAccountIds);
                if (ObjectUtils.isEmpty(tbTokens)) {
                    return;
                }
                Map<Long, TbToken> map = tbTokens.stream().collect(Collectors.toMap(TbToken::getId, Function.identity()));
                for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                    TbToken tbToken;
                    if (Objects.isNull(tbToken = map.get(relAccount.getAccountId()))) {
                        continue;
                    }
                    relAccount.setUserName(tbToken.getUserName());
                    relAccount.setAuthTime(tbToken.getAuthTime());
                    relAccount.setExptime(tbToken.getExptime());
                    relAccount.setRemark(tbToken.getRemark());
                    relAccount.setTurnlink(Tools.getInteger(tbToken.getTurnlink()));
                }
                return;
            // 京东
            case 1:
                List<Long> jdAccountIds = new ArrayList<>();
                List<Long> jdTlbAccountIds = new ArrayList<>();
                // 遍历
                filterTokenAccountId(relAccounts, jdAccountIds, jdTlbAccountIds);
//                Map<Integer, List<Long>> jdTypeAndIdMap = relAccounts.stream().collect(Collectors.groupingBy(TurnLinkLeagueSettingAccount::getAccountType, Collectors.mapping(TurnLinkLeagueSettingAccount::getAccountId, Collectors.toList())));
//                List<Long> jdAccountIds = jdTypeAndIdMap.get(ACCOUNT_TYPE_0);
//                List<Long> jdTlbAccountIds = jdTypeAndIdMap.get(ACCOUNT_TYPE_1);
                if (ObjectUtils.isNotEmpty(jdAccountIds)) {
                    List<JdToken> jdTokens = jdTokenService.listJdToken(merId, leagueAccountIds);
                    Map<Long, JdToken> jdMap = jdTokens.stream().collect(Collectors.toMap(JdToken::getId, Function.identity()));
                    for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                        JdToken jdToken;
                        if (Objects.isNull(jdToken = jdMap.get(relAccount.getAccountId()))) {
                            continue;
                        }
                        relAccount.setUnionId(jdToken.getUnionId());
                        relAccount.setRemark(jdToken.getRemark());
                        relAccount.setDefPid(jdToken.getDefPid());
                    }
                }
                fillTlbTokenInfo(merId, relAccounts, jdTlbAccountIds);
                break;
            // 拼多多
            case 2:
                Map<Integer, List<Long>> typeAndIdMap = relAccounts.stream().collect(Collectors.groupingBy(TurnLinkLeagueSettingAccount::getAccountType, Collectors.mapping(TurnLinkLeagueSettingAccount::getAccountId, Collectors.toList())));
                List<Long> pddAccountIds = typeAndIdMap.get(ACCOUNT_TYPE_0);
                List<Long> tlbAccountIds = typeAndIdMap.get(ACCOUNT_TYPE_1);
                if (ObjectUtils.isNotEmpty(pddAccountIds)) {
                    List<PddToken> pddTokens = pddTokenService.listPddToken(merId, pddAccountIds);
                    Map<Long, PddToken> pddMap = pddTokens.stream().collect(Collectors.toMap(PddToken::getId, Function.identity()));
                    for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                        if (!relAccount.getAccountType().equals(ACCOUNT_TYPE_0)) {
                            continue;
                        }
                        PddToken pddToken;
                        if (Objects.isNull(pddToken = pddMap.get(relAccount.getAccountId()))) {
                            continue;
                        }
                        relAccount.setUserId(pddToken.getUserId());
                        relAccount.setAccessToken(pddToken.getAccessToken());
                        relAccount.setExpirestime(ObjectUtils.defaultIfNull(pddToken.getExpiresin(), 0) + ObjectUtils.defaultIfNull(pddToken.getAuthTime(), 0));
                        relAccount.setDefPid(pddToken.getDefPid());
                        relAccount.setRemark(pddToken.getRemark());
                    }
                }
                fillTlbTokenInfo(merId, relAccounts, tlbAccountIds);
                break;
            // 唯品会
            case 3:
                List<Long> vphAccountIds = new ArrayList<>();
                List<Long> vphTlbAccountIds = new ArrayList<>();
                // 遍历
                filterTokenAccountId(relAccounts, vphAccountIds, vphTlbAccountIds);

                if (ObjectUtils.isNotEmpty(vphAccountIds)) {
                    List<VphToken> vphTokens = vphTokenService.listVphToken(merId, leagueAccountIds);
                    Map<Long, VphToken> vphMap = vphTokens.stream().collect(Collectors.toMap(VphToken::getId, Function.identity()));
                    for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                        VphToken vphToken;
                        if (Objects.isNull(vphToken = vphMap.get(relAccount.getAccountId()))) {
                            continue;
                        }
                        relAccount.setOpenId(vphToken.getOpenId());
                        relAccount.setAccessToken(vphToken.getAccessToken());
                        relAccount.setAuthTime(vphToken.getAuthTime());
                        relAccount.setExpirestime(vphToken.getExpiresTime());
                        relAccount.setRemark(vphToken.getRemark());
                    }
                }
                fillTlbTokenInfo(merId, relAccounts, vphTlbAccountIds);
                break;
            // 抖音
            case 11:
                Map<Integer, List<Long>> dyTypeAndIdMap = relAccounts.stream().collect(Collectors.groupingBy(TurnLinkLeagueSettingAccount::getAccountType, Collectors.mapping(TurnLinkLeagueSettingAccount::getAccountId, Collectors.toList())));
                List<Long> dyAccountIds = dyTypeAndIdMap.get(ACCOUNT_TYPE_2);
                List<Long> dyTlbAccountIds = dyTypeAndIdMap.get(ACCOUNT_TYPE_1);
                if (ObjectUtils.isNotEmpty(dyAccountIds)) {
                    List<DyToken> dyTokens = dyTokenService.listDyToken(merId, dyAccountIds);
                    Map<Long, DyToken> dyMap = dyTokens.stream().collect(Collectors.toMap(DyToken::getId, Function.identity()));
                    for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                        if (!relAccount.getAccountType().equals(ACCOUNT_TYPE_2)) {
                            continue;
                        }
                        DyToken pddToken;
                        if (Objects.isNull(pddToken = dyMap.get(relAccount.getAccountId()))) {
                            continue;
                        }
                        relAccount.setAccessToken(pddToken.getAccessToken());
                        relAccount.setUserName(pddToken.getName());
                        relAccount.setExpirestime(ObjectUtils.defaultIfNull(pddToken.getExptime(), 0));
                        relAccount.setDefPid(pddToken.getPid());
                        relAccount.setRemark(pddToken.getRemark());
                        relAccount.setAppId(pddToken.getAppId());
                        relAccount.setAppKey(pddToken.getAccessToken());
                    }
                }
                fillTlbTokenInfo(merId, relAccounts, dyTlbAccountIds);
                break;
            // 快手
            case 12:
                Map<Integer, List<Long>> ksTypeAndIdMap = relAccounts.stream().collect(Collectors.groupingBy(TurnLinkLeagueSettingAccount::getAccountType, Collectors.mapping(TurnLinkLeagueSettingAccount::getAccountId, Collectors.toList())));
                List<Long> ksAccountIds = ksTypeAndIdMap.get(ACCOUNT_TYPE_0);
                List<Long> ksTlbAccountIds = ksTypeAndIdMap.get(ACCOUNT_TYPE_1);
//                if (ObjectUtils.isNotEmpty(ksAccountIds)) {
//                    List<DyToken> dyTokens = dyTokenService.listDyToken(merId, ksAccountIds);
//                    Map<Long, DyToken> dyMap = dyTokens.stream().collect(Collectors.toMap(DyToken::getId, Function.identity()));
//                    for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
//                        if (!relAccount.getAccountType().equals(ACCOUNT_TYPE_0)) {
//                            continue;
//                        }
//                        DyToken pddToken;
//                        if (Objects.isNull(pddToken = dyMap.get(relAccount.getAccountId()))) {
//                            continue;
//                        }
//                        relAccount.setAccessToken(pddToken.getAccessToken());
//                        relAccount.setUserName(pddToken.getName());
//                        relAccount.setExpirestime(ObjectUtils.defaultIfNull(pddToken.getExptime(), 0));
//                        relAccount.setDefPid(pddToken.getPid());
//                        relAccount.setRemark(pddToken.getRemark());
//                    }
//                }
                fillTlbTokenInfo(merId, relAccounts, ksTlbAccountIds);
                break;
            default:
                throw new BusinessException("平台类型错误");
        }
    }

    private void fillTlbTokenInfo(Long merId, List<TurnLinkLeagueSettingAccount> relAccounts, List<Long> vphTlbAccountIds) {
        if (ObjectUtils.isNotEmpty(vphTlbAccountIds)) {
            List<TlbToken> tlbTokens = tlbTokenService.listTlbToken(merId, vphTlbAccountIds);
            Map<Long, TlbToken> pddMap = tlbTokens.stream().collect(Collectors.toMap(TlbToken::getId, Function.identity()));
            for (TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                if (!relAccount.getAccountType().equals(ACCOUNT_TYPE_1)) {
                    continue;
                }
                TlbToken tlbToken;
                if (Objects.isNull(tlbToken = pddMap.get(relAccount.getAccountId()))) {
                    continue;
                }
                relAccount.setAppKey(tlbToken.getAppKey());
                relAccount.setAppId(tlbToken.getAppId());
                relAccount.setRemark(tlbToken.getRemark());
            }
        }
    }

    @Override
    public TurnLinkLeagueSettingVo getTurnLinkLeagueSettingByPlatform(Long merId, Integer platform) {

        LambdaQueryWrapper<TlLeagueSettingDo> condition = Wrappers.lambdaQuery(TlLeagueSettingDo.class);
        condition.eq(TlLeagueSettingDo::getMerId, merId).eq(TlLeagueSettingDo::getPlatform, platform);
        TlLeagueSettingDo one = this.getOne(condition);
        if (Objects.isNull(one)) {
            throw new BusinessException("转链联盟配置信息不存在");
        }
        TurnLinkLeagueSettingVo turnLinkLeagueSettingVo = convertFromDo(one);

        List<TlLeagueSettingRelDo> relList = tlLeagueSettingRelService.listBySettingId(merId, one.getId());
        if (ObjectUtils.isEmpty(relList)) {
            return turnLinkLeagueSettingVo;
        }
        List<TurnLinkLeagueSettingAccount> accounts = convertFromDo(relList);
        fillLeagueAccountInfo(merId, one, accounts);
        // 如果平台是淘宝解析域名配置
        fillDomainInfoWithTb(merId, turnLinkLeagueSettingVo);
        turnLinkLeagueSettingVo.setRelAccounts(accounts);
        return turnLinkLeagueSettingVo;
    }

    public List<TurnLinkLeagueSettingAccount> convertFromDo(List<TlLeagueSettingRelDo> settingRelDos) {

        if (ObjectUtils.isEmpty(settingRelDos)) {
            return Lists.newArrayList();
        }

        List<TurnLinkLeagueSettingAccount> result = new ArrayList<>(settingRelDos.size());

        for (TlLeagueSettingRelDo settingRelDo : settingRelDos) {
            TurnLinkLeagueSettingAccount turnLinkLeagueSettingAccount = convertFromDo(settingRelDo);
            result.add(turnLinkLeagueSettingAccount);
        }
        return result;
    }

    private TurnLinkLeagueSettingAccount convertFromDo(TlLeagueSettingRelDo settingRelDo) {
        TurnLinkLeagueSettingAccount turnLinkLeagueSettingAccount = new TurnLinkLeagueSettingAccount();
        turnLinkLeagueSettingAccount.setId(settingRelDo.getId());
        turnLinkLeagueSettingAccount.setPromotion(StringUtils.isEmpty(settingRelDo.getExt()) ? Lists.newArrayList() : JSON.parseArray(settingRelDo.getExt(), TurnLinkLeagueSettingVo.TurnLinkPromotion.class));
        turnLinkLeagueSettingAccount.setAccountId(settingRelDo.getLeagueAccountId());
        turnLinkLeagueSettingAccount.setAccountType(settingRelDo.getAccountType());
        return turnLinkLeagueSettingAccount;
    }


    public TurnLinkLeagueSettingVo convertFromDo(TlLeagueSettingDo settingDo) {
        TurnLinkLeagueSettingVo turnLinkLeagueSettingVo = new TurnLinkLeagueSettingVo();
        turnLinkLeagueSettingVo.setId(settingDo.getId());
        turnLinkLeagueSettingVo.setPlatform(settingDo.getPlatform());

        turnLinkLeagueSettingVo.setExt(StringUtils.isNotBlank(settingDo.getExt()) ? JSON.parseObject(settingDo.getExt()) : null);
        return turnLinkLeagueSettingVo;
    }

    @Override
    public TurnLinkGenerateVo turnLink(TurnLinkGenerateDto generateDto) {

        Long settingId = generateDto.getSettingId();

        TlLeagueSettingDo settingDo = this.getById(settingId);
        if (Objects.isNull(settingDo)) {
            throw new BusinessException("联盟转链配置不存在");
        }

        PlatformTypeEnum byId = PlatformTypeEnum.getById(generateDto.getPlatform());
        if (Objects.isNull(byId)) {
            throw new BusinessException("平台类型不存在");
        }
        SimpleTurnLinkDto turnLinkDto = new SimpleTurnLinkDto();
        turnLinkDto.setMerId(generateDto.getMerId());
        turnLinkDto.setPid(generateDto.getPid());
        turnLinkDto.setCouponId(generateDto.getCouponId());
        turnLinkDto.setTokenId(generateDto.getTokenId());
        // 商品链接
        if (generateDto.getGoodsId().contains("http")) {
            turnLinkDto.setUrl(generateDto.getGoodsId());
        }
        // 商品ID
        else {
            turnLinkDto.setItemId(generateDto.getGoodsId());
        }

        String ext = settingDo.getExt();
        // 淘宝链接处理
        if (PlatformTypeEnum.PT_TAOBAO.equals(byId)) {
            if (StringUtils.isNotBlank(ext)) {
                JSONObject extJson = JSON.parseObject(ext);
                if (Objects.nonNull(extJson)) {
                    Long middle_page_domain = extJson.getLong("middle_page_domain");
                    // 如果没有设置值,则默认使用时官方域名
                    if (Objects.isNull(middle_page_domain)) {
                        turnLinkDto.setMiddlePageDomainId(0L);
                    }
                    // 2表示为页面参数模式
                    else if (middle_page_domain != 2L) {
                        turnLinkDto.setMiddlePageDomainId(middle_page_domain);
                    }
                    // 设置中间页连接即可
                    else {
                        turnLinkDto.setMiddlePageUrl(extJson.getString("middle_page_link"));
                    }
                }
            }
        }

        if (PlatformTypeEnum.PT_DY.equals(byId) || PlatformTypeEnum.PT_KS.equals(byId)) {
            turnLinkDto.setPwd(generateDto.getGoodsId());
            turnLinkDto.setItemId(null);
        }

        log.info("turnLink req param: {}", JSON.toJSONString(turnLinkDto));

        UzaiRespVo<SimpleTurnlinkVo> turnLinkRes;
        switch (byId) {
            case PT_TAOBAO:
                turnLinkRes = uzaiTurnlinkFeignService.tbTurnlinkSimple(turnLinkDto);
                break;
            case PT_JD:
                turnLinkRes = uzaiTurnlinkFeignService.jdTurnlinkSimple(turnLinkDto);
                break;
            case PT_PDD:
                turnLinkRes = uzaiTurnlinkFeignService.pddTurnlinkSimple(turnLinkDto);
                break;
            case PT_VPH:
                turnLinkRes = uzaiTurnlinkFeignService.vphTurnlinkSimple(turnLinkDto);
                break;
            case PT_DY:
                turnLinkRes = uzaiTurnlinkFeignService.dyTurnlinkSimple(turnLinkDto);
                break;
            case PT_KS:
                turnLinkRes = uzaiTurnlinkFeignService.ksTurnlinkSimple(turnLinkDto);
                break;
            default:
                throw new BusinessException("平台类型不支持");
        }
        log.info("turnLink res: {}", JSON.toJSONString(turnLinkRes));
        if (turnLinkRes.getCode() != 200) {
            throw new BusinessException(turnLinkRes.getMsg());
        }
        SimpleTurnlinkVo turnLink = turnLinkRes.getData();

        TurnLinkGenerateVo generateVo = new TurnLinkGenerateVo();
        generateVo.setLink(turnLink.getBuyUrl());
        generateVo.setBuyPwd(turnLink.getPurePwd());

        if (byId.equals(PlatformTypeEnum.PT_PDD) || StringUtils.isNotBlank(turnLink.getPddAuthUrl())) {
            generateVo.setPddAuthUrl(turnLink.getPddAuthUrl());
        }

        return generateVo;
    }

    @Override
    public TurnLinkGoodsAnalyzeVo analyzeGoods(TurnLinkGoodsAnalyzeDto goodsAnalyze) {
        TextConvertGoodsDto textConvertGoodsDto = new TextConvertGoodsDto();

        textConvertGoodsDto.setMerId(goodsAnalyze.getMerId());
        textConvertGoodsDto.setText(goodsAnalyze.getContent());

        log.warn("analyzeGoods req: {}", JSON.toJSONString(textConvertGoodsDto));
        UzaiRespVo<ConvertGoodsDto> analyzeRes = clientApiService.convertGoods(textConvertGoodsDto);
        log.warn("analyzeGoods res: {}", JSON.toJSONString(analyzeRes));
        if (analyzeRes.getCode() != 200) {
            throw new BusinessException("商品解析失败");
        }
        ConvertGoodsDto data = analyzeRes.getData();
        if (Objects.isNull(data)) {
            throw new BusinessException("商品解析失败");
        }
        List<Integer> supportPlatform = Lists.newArrayList(PlatformTypeEnum.PT_TAOBAO_VALUE, PlatformTypeEnum.PT_JD_VALUE, PlatformTypeEnum.PT_VPH_VALUE, PlatformTypeEnum.PT_PDD_VALUE, PlatformTypeEnum.PT_DY_VALUE, PlatformTypeEnum.PT_KS_VALUE);
        if (!supportPlatform.contains(data.getPlatform().getId())) {
            throw new BusinessException("平台暂不支持解析");
        }
        TurnLinkGoodsAnalyzeVo turnLinkGoodsAnalyzeVo = new TurnLinkGoodsAnalyzeVo();
        // 商品ID
        if (CollectionUtil.isNotEmpty(data.getGoodsId())) {
            String goodsId = data.getGoodsId().stream().findFirst().orElse("");
            turnLinkGoodsAnalyzeVo.setGoodsId(goodsId);
            turnLinkGoodsAnalyzeVo.setGoodsIds(data.getGoodsId());
        }
        // 商品链接
        else if (CollectionUtil.isNotEmpty(data.getGoodsUrl())) {
            String goodsUrl = data.getGoodsUrl().stream().findFirst().orElse("");
            turnLinkGoodsAnalyzeVo.setGoodsId(goodsUrl);
            turnLinkGoodsAnalyzeVo.setGoodsIds(data.getGoodsUrl());
        }
        turnLinkGoodsAnalyzeVo.setPlatform(data.getPlatform().getId());
        if (StringUtils.isEmpty(turnLinkGoodsAnalyzeVo.getGoodsId())) {
            String goodsId = getGoodsIdByPwdStr(goodsAnalyze.getMerId(), goodsAnalyze.getContent(), turnLinkGoodsAnalyzeVo.getPlatform());
            turnLinkGoodsAnalyzeVo.setGoodsId(goodsId);
            turnLinkGoodsAnalyzeVo.setGoodsIds(Lists.newArrayList(goodsId));
        }
        return turnLinkGoodsAnalyzeVo;
    }

    // 根据淘口令获取到商品ID
    private String getGoodsIdByPwdStr(Long merId, String content, Integer platform) {
        if (!Objects.equals(PlatformTypeEnum.PT_TAOBAO.getId(), platform)) {
            return "";
        }
        // 获取有效的tb联盟账号
        TbToken tbToken = tbTokenService.getOneValidTbToken(merId);
        if (Objects.isNull(tbToken)) {
            throw new BusinessException("淘宝联盟账号不存在");
        }

        TbPwdAnalysisDto tbPwdAnalysisDto = new TbPwdAnalysisDto();
        tbPwdAnalysisDto.setPwd(content);
        tbPwdAnalysisDto.setTokenId(tbToken.getId());

        // 调用淘口令解析
        UzaiRespVo<TbPwdAnalysisVo> tbPwdAnalysisVoUzaiRespVo = uzaiTurnlinkFeignService.tbPwdAnalysis(tbPwdAnalysisDto);
        log.info("tbPwdAnalysis result: {}", JSON.toJSONString(tbPwdAnalysisVoUzaiRespVo));
        if (tbPwdAnalysisVoUzaiRespVo.getCode() != 200) {
            throw new BusinessException(tbPwdAnalysisVoUzaiRespVo.getMsg());
        }
        TbPwdAnalysisVo data = tbPwdAnalysisVoUzaiRespVo.getData();
        return data.getItemId();
    }

    @Override
    public String generateShortLink(TurnShortLinkDto shortLinkDto) {
        GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
        generateShortUrlDto.setUrl(shortLinkDto.getLink());
        generateShortUrlDto.setMerId(shortLinkDto.getMerId());

        UzaiRespVo<String> shortUrlRes = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
        if (shortUrlRes.getCode() != 200) {
            throw new BusinessException(shortUrlRes.getMsg());
        }
        return shortUrlRes.getData();
    }

    @Override
    public String generateShortLink(String link, Long merId) {
        GenerateShortUrlDto generateShortUrlDto = new GenerateShortUrlDto();
        generateShortUrlDto.setUrl(link);
        generateShortUrlDto.setMerId(merId);

        UzaiRespVo<String> shortUrlRes = uzaiTurnlinkFeignService.generateShortUrl(generateShortUrlDto);
        if (shortUrlRes.getCode() != 200) {
            throw new BusinessException(shortUrlRes.getMsg());
        }
        return shortUrlRes.getData();
    }

    @Override
    public TurnLinkGenerateVo activityTurnLink(TurnLinkGenerateDto generateDto) {

        PlatformTypeEnum byId = PlatformTypeEnum.getById(generateDto.getPlatform());
        if (Objects.isNull(byId)) {
            throw new BusinessException("平台类型不存在");
        }
        SimpleTurnLinkDto turnLinkDto = new SimpleTurnLinkDto();
        turnLinkDto.setMerId(generateDto.getMerId());
        turnLinkDto.setPid(generateDto.getPid());
        turnLinkDto.setTokenId(generateDto.getTokenId());

        Long settingId = generateDto.getSettingId();

        TlLeagueSettingDo settingDo = this.getById(settingId);
        if (Objects.isNull(settingDo)) {
            throw new BusinessException("联盟转链配置不存在");
        }
        String ext = settingDo.getExt();
        if (StringUtils.isNotBlank(ext)) {
            JSONObject extJson = JSON.parseObject(ext);
            if (Objects.nonNull(extJson)) {
                Long middle_page_domain = extJson.getLong("middle_page_domain");
                // 如果没有设置值,则默认使用时官方域名
                if (Objects.isNull(middle_page_domain)) {
                    turnLinkDto.setMiddlePageDomainId(0L);
                }
                // 2表示为页面参数模式
                else if (middle_page_domain != 2L) {
                    turnLinkDto.setMiddlePageDomainId(middle_page_domain);
                }
                // 设置中间页连接即可
                else {
                    turnLinkDto.setMiddlePageUrl(extJson.getString("middle_page_link"));
                }
            }
        }

        if (Objects.equals(PlatformTypeEnum.PT_TAOBAO.getId(), generateDto.getPlatform())) {
            MarketingActivity marketingActivity;
            if (Objects.isNull(marketingActivity = marketingActivityMapper.selectByActivityId(generateDto.getActivityId()))) {
                throw new BusinessException("活动不存在");
            }
            turnLinkDto.setActivityId(generateDto.getActivityId());
            turnLinkDto.setActivityImg(marketingActivity.getActivityImg());
            turnLinkDto.setPageModelId(generateDto.getPageModelId());

            log.info("activity turnLink req param: {}", JSON.toJSONString(turnLinkDto));

            UzaiRespVo<SimpleTurnlinkVo> turnLinkRes = uzaiTurnlinkFeignService.tbActivityTurnlink(turnLinkDto);
            log.info("activity turnLink res: {}", JSON.toJSONString(turnLinkRes));
            if (turnLinkRes.getCode() != 200) {
                throw new BusinessException(turnLinkRes.getMsg());
            }
            SimpleTurnlinkVo turnLink = turnLinkRes.getData();

            TurnLinkGenerateVo generateVo = new TurnLinkGenerateVo();
            generateVo.setLink(turnLink.getBuyUrl());
            generateVo.setBuyPwd(turnLink.getPurePwd());
            return generateVo;
        } else if (Objects.equals(PlatformTypeEnum.PT_JD.getId(), generateDto.getPlatform())) {
            turnLinkDto.setUrl(generateDto.getActivityLink());
            turnLinkDto.setJdCommand(1);

            log.info("jd activity turnLink req param: {}", JSON.toJSONString(turnLinkDto));

            UzaiRespVo<SimpleTurnlinkVo> turnLinkRes = uzaiTurnlinkFeignService.jdTurnlinkSimple(turnLinkDto);
            log.info("jd activity turnLink res: {}", JSON.toJSONString(turnLinkRes));
            if (turnLinkRes.getCode() != 200) {
                throw new BusinessException(turnLinkRes.getMsg());
            }
            SimpleTurnlinkVo turnLink = turnLinkRes.getData();

            TurnLinkGenerateVo generateVo = new TurnLinkGenerateVo();
            generateVo.setLink(turnLink.getBuyUrl());
            if (StringUtils.isNotBlank(turnLink.getJdCommand())) {
                generateVo.setBuyPwd(turnLink.getJdCommand());
            }
            return generateVo;
        } else if (Objects.equals(PlatformTypeEnum.PT_VPH.getId(), generateDto.getPlatform())) {
            turnLinkDto.setUrl(generateDto.getActivityLink());

            log.info("vph activity turnLink req param: {}", JSON.toJSONString(turnLinkDto));

            UzaiRespVo<SimpleTurnlinkVo> turnLinkRes = uzaiTurnlinkFeignService.vphTurnlinkSimple(turnLinkDto);
            log.info("vph activity turnLink res: {}", JSON.toJSONString(turnLinkRes));
            if (turnLinkRes.getCode() != 200) {
                throw new BusinessException(turnLinkRes.getMsg());
            }
            SimpleTurnlinkVo turnLink = turnLinkRes.getData();

            TurnLinkGenerateVo generateVo = new TurnLinkGenerateVo();
            generateVo.setLink(turnLink.getBuyUrl());
            if (StringUtils.isNotBlank(turnLink.getJdCommand())) {
                generateVo.setBuyPwd(turnLink.getJdCommand());
            }
            return generateVo;
        }
        throw new BusinessException("活动转链暂不支持");
    }

    @Override
    public List<SelectVo> listMarketingActivity() {

        List<MarketingActivity> marketingActivities = marketingActivityMapper.selectAll();
        if (ObjectUtils.isEmpty(marketingActivities)) {
            return Lists.newArrayList();
        }
        List<SelectVo> result = new ArrayList<>();

        for (MarketingActivity marketingActivity : marketingActivities) {
            SelectVo selectVo = new SelectVo();
            if (Objects.equals(PlatformTypeEnum.PT_TAOBAO.getId(), marketingActivity.getPlatform())) {
                selectVo.setKey(marketingActivity.getActivityId());
                selectVo.setValue(marketingActivity.getActivityName());
            } else if (Objects.equals(PlatformTypeEnum.PT_JD.getId(), marketingActivity.getPlatform())) {
                selectVo.setKey(marketingActivity.getActivityId());
                selectVo.setValue(marketingActivity.getActivityName());
                selectVo.setLink(marketingActivity.getActivityLink());
            } else if (Objects.equals(PlatformTypeEnum.PT_VPH.getId(), marketingActivity.getPlatform())) {
                selectVo.setKey(marketingActivity.getActivityId());
                selectVo.setValue(marketingActivity.getActivityName());
                selectVo.setLink(marketingActivity.getActivityLink());
            }
            selectVo.setPlatform(marketingActivity.getPlatform());
            result.add(selectVo);
        }
        return result;
    }
}
